#!/bin/bash

# controb ------>> /var/spool/cron/crontabs/root
# 1 0 * * *  bash /root/xadserver/openresty/xad_cut_nginx_log.sh

#LOG_PATH=/etc/nginx/logs/xad
#YESTERDAY=$(date -d "yesterday" +%Y-%m-%d)
#PID=/var/run/nginx/nginx.pid

#mv ${LOG_PATH}access.log ${LOG_PATH}access-${YESTERDAY}.log
#mv ${LOG_PATH}error.log ${LOG_PATH}error-${YESTERDAY}.log
#
#kill -USR1 `cat ${PID}`


# original ngx log path
source_log_path=/data/openresty/logs/prm.bao5.com.cn/
# new path
dest_log_path=/data/openresty/logs/prm.bao5.com.cn/

#定义log文件的名称，以每天为单位，定义日志的前缀为昨天的日期，因为定时任务拟在凌晨零点后执行。
yesterday=$(date -d "yesterday" +%Y%m%d)
#echo ${yesterday}
#rm -rf ${dest_log_path}/*

#
dest_log_path_access=${dest_log_path}/nginx_access_${yesterday}.log
dest_log_path_error=${dest_log_path}/nginx_error_${yesterday}.log
#
dest_log_path_access_gz=${dest_log_path}/nginx_access_${yesterday}.tar.gz
dest_log_path_error_gz=${dest_log_path}/nginx_error_${yesterday}.tar.gz

#
mv ${source_log_path}/access.log ${dest_log_path_access}
mv ${source_log_path}/error.log  ${dest_log_path_error}

#移动后，重新向nginx的主进程发送信息，令nginx的主进程将日志重新打开。否则日志将会继续写到mv后的路径中
kill -USR1 `ps axu | grep "nginx: master process" | grep -v grep | awk '{print $2}'`
#kill -USR1 cat /usr/local/nginx/logs/nginx.pid

cd ${dest_log_path}

#tar -zcvf ${dest_log_path_access_gz} ${dest_log_path_access} --remove-files
#tar -zcvf ${dest_log_path_error_gz} ${dest_log_path_error} --remove-files

tar -zcvf ${dest_log_path_access_gz} ${dest_log_path_access} && rm -rf ${dest_log_path_access}
tar -zcvf ${dest_log_path_error_gz} ${dest_log_path_error} && rm -rf ${dest_log_path_error}

# 进入日志的路径，查询前天前的日志，然后将其删掉
#find . -mtime +7 -name "*20[1-9][3-9]*" | xargs rm -rf

exit 0
